import { resetData, callType } from '@/utils'
import NavBar from '@/components/NavBar'
export const tableMixins = {
  data() {
    return {
      resetData,
      initVal: {
        page: {
          pageNo: 1,
          pageSize: 10
        }
      },
      isLoading: false,
      finished: true,
      error: false,
      getDataApi: '',
      listData: [],
      callType
    }
  },
  created() {
    this.onLoad()
  },
  methods: {
    onLoad(val) {
      if (!this.getDataApi) {
        this.$toast.fail('请在data里定义请求的api!(getDataApi:api)')
        return
      }
      if (val && val === 'reset') {
        this.initVal.page.pageNo = 1
      }
      const tempObj = this._.cloneDeep((this.initVal))
      for (const key in tempObj) {
        if (this.callType(tempObj[key]) === 'Array' && (tempObj[key].length === 0 || (!tempObj[key][0] && tempObj[key][0] !== 0))) {
          tempObj[key] = void 0
        }
      }
      this.isLoading = true
      this.$loading.show()
      this.getDataApi(tempObj).then(res => {
        this.error = false
        if (val === 'reset') {
          this.listData = res.data.list
        } else {
          this.listData = this.listData.concat(res.data.list)
        }

        if (this.listData.length === res.data.count) {
          this.finished = true
        } else {
          this.initVal.page.pageNo++
          this.finished = false
        }
        this.isLoading = false
      }).catch(() => {
        this.isLoading = false
        this.finished = true
        this.error = true
      })
        .finally(() => {
          this.$loading.hide()
        })
    },
    resetData() {
      resetData(this, 'initVal')
      this.onLoad('reset')
    },
    searchData() {
      this.onLoad('reset')
    }
  },
  computed: {
    userId() {
      return this.$store.state.userInfo.userId
    }
  },
  components: {
    NavBar
  }
}
